package org.example.controller;

import org.example.Entity.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传API
 */
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    // 项目根目录下的pictures目录路径
    private static String UPLOAD_DIR = Paths.get("").toAbsolutePath().toString() + "/pictures/";

    @PostMapping("/picture")
    public Result<Map> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("图片为空！");
        }

        try {
            // 确保pictures目录存在
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件名称并生成存储路径
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
            File dest = filePath.toFile();

            // 保存文件
            file.transferTo(dest);

            // 返回文件的完整路径
            String fullPath = dest.getAbsolutePath();
            Map<String,String> map = new HashMap();
            map.put("picture_path", fullPath);
            return Result.success(map);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传图片失败！");
        }
    }
}